package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.*;
import com.example.demo.service.*;
import com.example.demo.util.TokenUtils;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/weifen")
public class WeiFenController {
    @Autowired
    WeifenService weifenService;
@Autowired
    GoodsService goodsService;
@Autowired
    UserService userService;
@Autowired
    RecordService recordService;
    @PostMapping
    public Result save(@RequestBody Weifen weifen){
        weifenService.saveOrUpdate(weifen);
        return Result.suc();
    }

    @PostMapping("/addOrder")
    public Result addOrder(@RequestBody Orders orders) {
        Weifen weifen = weifenService.addOrder(orders);
        weifenService.save(weifen);
        return Result.suc();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        weifenService.removeById(id);
        return Result.suc();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        weifenService.removeByIds(ids);
        return Result.suc();
    }

    @GetMapping("/page")
    public Result findPage(
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Weifen> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        Page<Weifen> page = weifenService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.suc(page);
    }
    @PostMapping("/addTwo")
    public Result addOrder(@RequestBody Weifen weifen) {
        Record record = new Record();
QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name",weifen.getGoods());
     List<Goods> list=  goodsService.list(queryWrapper);
        Goods goods = list.get(0);
        User admin= TokenUtils.getCurrentUser();
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("name",weifen.getStaff());
     List<User> list1 =   userService.list(queryWrapper1);
    User staff =  list1.get(0);
     record.setGoods(goods.getId());
     record.setAdminid(admin.getId());
     record.setUserid(staff.getId());
     int n = weifen.getNum();
       int m = -n;
     record.setCount(m);
     String remark = "正常出货";
     record.setRemark(remark);
        recordService.save(record);
        int num = goods.getCount()+m;
        goods.setCount(num);
        goodsService.updateById(goods);
        return Result.suc();
    }
}
